package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import entity.Flower;
import service.FlowerService;
import utils.Page;

@Controller
@RequestMapping("/main/flower")
public class FlowerController extends BaseController{
    @Autowired
    private FlowerService flowerService;

    @RequestMapping("/page")
    public String page(Model model, Flower condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        Page<Flower> page = null;
        try {
            // 查询用户的分页信息
            page = flowerService.getFlowers(condition, pageNo, pageSize);
            // 将分页数据、角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo", page);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "/flower/page";
    }
    @GetMapping("/save")
    public String insert(Model model){
        try {
            // 回显数据时需要 sysUser，这里给个空对象避免出错
            model.addAttribute("flower", new Flower());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "/flower/save";
    }
    @PostMapping("/save")
    public  String save(Flower flower) {
        boolean ok = false;
        try {
            if (flower.getFlowerId() == null) {
                ok = flowerService.insert(flower);
            } else {
//            ok = flowerService.insert(flower);
            }
            if (ok) {
                // 保存成功，跳回列表页面
                return redirect("/main/flower/page");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "/flower/save";
    }


}
